/*
*描述：此页面用于两个功能模块，分别是：KA活动的新活动初始化和Region活动的新活动初始化。其中Region活动初始化的时包含，发起正常的活动(ET、FG)和竞品活动发起(两者兼无)
*/
public with sharing class KAInitActivityForNTMKTListController {
   public Activity_Information__c ActivityInit{get;set;} //初始化活动对象
   public Resource_Allocation__c ResourceObj{get;set;}//初始化ET资源分配
   public Resource_Allocation__c FGResourceObj{get;set;}//初始化FG资源分配
   public List<ActivityResourceEntry> ETResourceEntryList{get;set;}//ET资源分配集合 
   public List<ActivityResourceEntry> FGResourceEntryList{get;set;}//FG资源分配集合 
   //public List<Resource_Allocation__c> resourceList{get;set;}//ET,FG资源总和
  //   public CommonAttribute PlaceAttribute{get;set;}//地域信息;
   public CommonAttribute ETPlaceAttribute{get;set;}//地域信息;
    public CommonAttribute FGPlaceAttribute{get;set;}//地域信息;
     public CommonAttribute CoPlaceAttribute{get;set;}//地域信息;
   public String RegionSelectedValue{get;set;}//选中的区域值
   public String SubRegionSelectedValue{get;set;}//选中片区的值
   public String AreaSelectedValue{get;set;}//区域选择的值
   public  List<Participator_Detail_Outlet__c> outletDetail{get;set;}
   public Map<String,ActivityParticipatorEntry> mapParticipatorAreaETList;  //ET参与列表
   public Map<String,ActivityParticipatorEntry >mapParticipatorAreaFGList;//FG参与列表
   public Map<String,ActivityParticipatorEntry >mapParticipatorAreaOtherList;//参与列表,保存两者兼无的数据
   public List<ActivityParticipatorEntry> ParticipatorAreaFGList{get;set;}//FG参与列表area集合
   public List<ActivityParticipatorEntry> ParticipatorAreaETList{get;set;}//ET参与列表，绑定到页面
   public List<ActivityParticipatorEntry> ParticipatorAreaOtherList{get;set;}//参与列表，绑定到页面，保存两者兼无的数据
    
    public List<ActivityCompetitionBrandEntry> CompetitionList{get;set;}//竞品信息
    public Boolean IsAdjustDisplay{get;set;}//调整KA资源按钮是否显示
    public String getTypeETOrFGOrAll{get;set;}//获得用户选择的ET、FG
    public CommonMethod commonMethod;
    public Boolean IsSubmit{get;set;}//是否显示保存提交按钮
    public Boolean IsSave{get;set;}//保存活动后显示下面的部分
    public String Set1ButtonText{get;set;}//第一步骤的按钮显示文本
    public Boolean IsCompetitionDisplay{get;set;}//竞品信息是否显示
    public Boolean IsSelectedAllCompetition{get;set;}//竟品费用全选
    public Boolean CheckParticipatorAll{get;set;}//参与者列表全选
    
     public String ETRegionSelectedValue{get;set;}//选中的区域值
    public String ETSubRegionSelectedValue{get;set;}//选中片区的值
    public String ETAreaSelectedValue{get;set;}//区域选择的值
    public String ETOutletTypeSelectedValue{get;set;}//门店类型选择的值 
    public String ETChannelSelectedValue{get;set;}//渠道选择的值  
    public String ETKASelectedValue{get;set;}
    
       public String FGRegionSelectedValue{get;set;}//选中的区域值
    public String FGSubRegionSelectedValue{get;set;}//选中片区的值
    public String FGAreaSelectedValue{get;set;}//区域选择的值
    public String FGOutletTypeSelectedValue{get;set;}//门店类型选择的值 
    public String FGChannelSelectedValue{get;set;}//渠道选择的值  
    public String FGKASelectedValue{get;set;}
    
       public String CoRegionSelectedValue{get;set;}//选中的区域值
    public String CoSubRegionSelectedValue{get;set;}//选中片区的值
    public String CoAreaSelectedValue{get;set;}//区域选择的值
    public String CoOutletTypeSelectedValue{get;set;}//门店类型选择的值 
    public String CoChannelSelectedValue{get;set;}//渠道选择的值  
    public String CoKASelectedValue{get;set;}
   
public User u{
 get{
   return commonMethod.getUserInfo();
 }
}   
 public String RecordId
   {
       get
       {
         if(System.currentPageReference().getParameters().get('id')!=null)
            return String.valueOf(System.currentPageReference().getParameters().get('id')).substring(0,15);  
         else
            return null;
       }
       set;
   }
   //活动类型,Region或KA活动
   public string ActivityType
   {
       get
       {
           return System.currentPageReference().getParameters().get('ActivityType');   
       }
   }
   public String RecordTypeId
    {
        get{        
                return System.currentPageReference().getParameters().get('RecordType'); 
         //  return '012O00000008WMk';         
           }  
        set;
    }
    public List<SelectOption> GetActivityTypeItem//活动类型，ET、FG
   {
       get;
       set;
   /*    {
            List<SelectOption> option=new List<SelectOption>();
            option.add(new SelectOption('ET','ET'));
            option.add(new SelectOption('FG','FG'));
            if(ActivityType=='Region')
                option.add(new SelectOption('两者兼无','两者兼无'));
            return option;
       }*/
   }
     //ET资源总数
     public decimal ETtotalResourceNum{
       get{
            decimal totalResourceNum=0;
            for(ActivityResourceEntry are:ETResourceEntryList ){
               totalResourceNum+=are.Res.Resource_Allocation_Number__c;
             }
             return totalResourceNum;
         }
     }
     //FG资源总数
    public decimal FGtotalResourceNum{
     get{
          decimal totalResourceNum=0;
           for(ActivityResourceEntry are:FGResourceEntryList ){
               totalResourceNum+=are.Res.Resource_Allocation_Number__c;
             }
          return totalResourceNum;
       }
    }
    public KAInitActivityForNTMKTListController(ApexPages.StandardController controller) {
        IsAdjustDisplay=false;
        IsCompetitionDisplay=true;
        Set1ButtonText='保存并继续';
        ActivityInit=new Activity_Information__c();
        ActivityInit.RecordTypeId=RecordTypeId;
        ActivityInit.Activity_Stage__c='草稿';
        ActivityInit.Activity_Type_State__c='正常';
       // ActivityInit.Activity_Type__c='KA';
       LoadUtils();
       
         if(ActivityInit.id!=NULL || RecordId!=NULL)//更新状态
       {
            ActivityInit=[Select Id,IsNcOrNotForRegion__c,Name,OwnerId,RecordTypeId, ASMConfirmDate__c, ASMFinishDate__c, Activity_End_Date__c,Regional_Activity_Type__c,
                                  Activity_Notice__c, Activity_Stage__c, Activity_Start_Date__c, Activity_Type_State__c, Activity_Type__c, 
                                  KAMConfirmDate__c, KAMFinishAdjustDate__c, NTMKTFinishApproveDate__c, RSMFinishApproveDate__c, 
                                  RTMFinishApproveDate__c, SRTMFinishApproveDate__c, SRTMFinishDate__c,Serial_Number__c
                                   FROM Activity_Information__c  where id=:RecordId];
                    //提交状态按钮不可用
           IsSubmit=false;     
           IsSave=false;   
           IsCompetitionDisplay=true;
           if(ActivityInit.id!=NULL)
           {
                IsSave=true;    
                 if(ActivityType=='Region')
                 {
                 //活动不为空，当活动不是两者兼无时，则默认显示ET          
                    IsCompetitionDisplay=true;    
                         
                 }
            }    
           if(IsSave)
                IsSubmit=true;           
           if(ActivityInit.OwnerId!=u.id || ActivityInit.Activity_Stage__c=='活动已取消' || ActivityInit.Activity_Stage__c=='总部已发起活动' || ActivityInit.Activity_Stage__c=='SRTM已发起活动' || ActivityInit.Activity_Stage__c=='SRTM已完成区域调整')
            {
               IsSubmit=false;
                IsCompetitionDisplay=false;
            }     
            LoadCompetitionBrandList();//加载竞品
         }
                     
    }
    //初始化变量
    public void init(){
          
            GetActivityTypeItem=new List<SelectOption>();
      //      GetActivityTypeItem.add(new SelectOption('ET','ET'));
          //  GetActivityTypeItem.add(new SelectOption('FG','FG'));
            if(ActivityType=='Region')
                GetActivityTypeItem.add(new SelectOption('ET','资源'));
                GetActivityTypeItem.add(new SelectOption('两者兼无','两者兼无'));
          
          
        if(outletDetail==NULL)
             outletDetail=new List<Participator_Detail_Outlet__c>();
           
        commonMethod=new CommonMethod();   
           
        ResourceObj=new Resource_Allocation__c();
        FGResourceObj=new Resource_Allocation__c();
      //  PlaceAttribute=new CommonAttribute();
        ETPlaceAttribute=new CommonAttribute();
         FGPlaceAttribute=new CommonAttribute();
          CoPlaceAttribute=new CommonAttribute();
        ETResourceEntryList=new List<ActivityResourceEntry>();
        FGResourceEntryList=new List<ActivityResourceEntry>();
        
       //参与列表
       if(ParticipatorAreaETList==NULL)
              ParticipatorAreaETList=new  List<ActivityParticipatorEntry>();//ET
       else
             ParticipatorAreaETList.clear();
       if(mapParticipatorAreaETList==NULL)
            mapParticipatorAreaETList=new Map<String,ActivityParticipatorEntry >();//ET Map 
        else
            mapParticipatorAreaETList.clear();
       if(ParticipatorAreaFGList==NULL)
            ParticipatorAreaFGList=new  List<ActivityParticipatorEntry>();//FG
       else
            ParticipatorAreaFGList.clear();
       if(mapParticipatorAreaFGList==NULL)
            mapParticipatorAreaFGList=new Map<String,ActivityParticipatorEntry>();//FG Map
       else
           mapParticipatorAreaFGList.clear();
           
       if(mapParticipatorAreaOtherList==NULL)
            mapParticipatorAreaOtherList=new Map<String,ActivityParticipatorEntry>();//FG Map
       else
           mapParticipatorAreaOtherList.clear();
           
        if(ParticipatorAreaOtherList==NULL)
            ParticipatorAreaOtherList=new  List<ActivityParticipatorEntry>();//FG
       else
            ParticipatorAreaOtherList.clear();
    }
   //加载初始化数据 
    public void LoadUtils(){ 
        init();
       
      //初始化资源分配信息
        if(RecordId!=NULL)
        {
             for(Resource_Allocation__c res:[Select id,Activity_Information_Name__c,
                                                             Product_Code__c, Product_Name__c, Resource_Allocation_Number__c, Resource_Type__c,Product_Name__r.Pack_Size_C__c, 
                                                             Allocation_Sum_Total__c FROM Resource_Allocation__c where Activity_Information_Name__c=:RecordId])
             {
                      res.ETOrFGCode__c=res.Product_Code__c;
                       if(res.Resource_Type__c=='ET')
                           ETResourceEntryList.add(new ActivityResourceEntry(false,res));    
                       else
                           FGResourceEntryList.add(new ActivityResourceEntry(false,res));     
               }         
    
             //初始化参与列表(area)
             for(ParticipatorArea__c area: [Select Activity_Name__c, KA_Status__c, KA__c, Type__c, OutletType__c, Channel__c, 
                                                                                   Sub_region__c, Region__c, Outlet_Sum_Total__c, Area__c,IsNCOrNot__c 
                                                                                   FROM ParticipatorArea__c where Activity_Name__c=: RecordId])
              {
                     String key=area.Region__c+area.Sub_region__c+area.Area__c+area.KA__c+area.OutletType__c+area.Channel__c;
                      if(area.Type__c=='ET')
                      {      
                          mapParticipatorAreaETList.put(key,new ActivityParticipatorEntry(false,area));
                          ParticipatorAreaETList.add(new ActivityParticipatorEntry(false,area));     
                      }
                      if(area.Type__c=='FG')
                      {
                          mapParticipatorAreaFGList.put(key,new ActivityParticipatorEntry(false,area));
                          ParticipatorAreaFGList.add(new ActivityParticipatorEntry(false,area));     
                      }           
                      if(area.Type__c=='其它')
                      {
                          mapParticipatorAreaOtherList.put(key,new ActivityParticipatorEntry(false,area));
                          ParticipatorAreaOtherList.add(new ActivityParticipatorEntry(false,area));     
                      }                                              
               }  
          }
    }
       //加载竞品信息
    public void LoadCompetitionBrandList()
    {
        if(CompetitionList==NULL)
            CompetitionList=new List<ActivityCompetitionBrandEntry>();
         else
             CompetitionList.clear();
        for(Activity_Competition_Brand_Information__c acbi: [select id,Competition_Cost_Source__c,
                                                                                         Competition_Cost_Type__c,Competition_Promotion_Type__c 
                                                                                          from  Activity_Competition_Brand_Information__c
                                                                                           where Activity_Information__c=:RecordId])
        {
            CompetitionList.add(new ActivityCompetitionBrandEntry(false,acbi));
        }
    }
  
 //添加ET资源
   public PageReference AddResource(){
     if(ResourceObj.Product_Name__c != NULL)
     {         
           commonMethod.AddResources('ET',ETResourceEntryList,ResourceObj); 
           ResourceObj=NULL;
           ResourceObj=new Resource_Allocation__c();    
       }     
      return null;
    }
   //添加FG资源
   public PageReference AddResourceFG(){
     if(FGResourceObj.Product_Name__c != NULL)
     {         
           commonMethod.AddResources('FG',FGResourceEntryList,FGResourceObj);
           FGResourceObj=NULL;
           FGResourceObj=new Resource_Allocation__c();    
       }     
      return null;
    }    
       //DeleteET资源
      public PageReference DelResource()
      {
        commonMethod.DelResource(ETResourceEntryList);
       return null;
      }
      //DeleteFG资源
      public PageReference DelResourceFG()
      {
        commonMethod.DelResource(FGResourceEntryList);
       return null;
      }
       //Reset资源
      public PageReference ResetALLData()
      {
       commonMethod.ResetALLData(ETResourceEntryList);
      return null;
      }
        //ResetFG资源
      public PageReference ResetALLDataFG()
      {
      commonMethod.ResetALLData(FGResourceEntryList);
      return null;
      }
   
       //添加ET参与者 
      public PageReference AddParticipator()
      {
        try{
        //KA/region活动从大区开始选
          if((ETPlaceAttribute.RegionSelectedValue==NULL || ETPlaceAttribute.RegionSelectedValue=='0') && 
           (ETPlaceAttribute.SubRegionSelectedValue==NULL || ETPlaceAttribute.SubRegionSelectedValue=='0') && 
           (ETPlaceAttribute.AreaSelectedValue==NULL || ETPlaceAttribute.AreaSelectedValue=='0'))
                throw new CustomException ('请选择一个地域');     
           if(ActivityType=='KA'){
                if(ETPlaceAttribute.KASelectedValue==NULL || ETPlaceAttribute.KASelectedValue=='0')
                    throw new CustomException ('请选择一个KA');      
           }     
         }catch(Exception ex)
             {
                 ApexPages.addMessages(ex);
                 return null;
             }
        if(ActivityType=='KA')// commonMethod.
          AddParticipators('ET',mapParticipatorAreaETList,ParticipatorAreaETList,ETPlaceAttribute,false,ActivityInit);
       else
           AddParticipators('ET',mapParticipatorAreaETList,ParticipatorAreaETList,ETPlaceAttribute,ActivityInit.IsNcOrNotForRegion__c,ActivityInit);
        //  System.assert(false,ETPlaceAttribute.RegionSelectedValue
        return null;
      }
       //添加FG参与者 
      public PageReference AddFGParticipator()
      {
        try{
          if((FGPlaceAttribute.RegionSelectedValue==NULL || FGPlaceAttribute.RegionSelectedValue=='0') && 
           (FGPlaceAttribute.SubRegionSelectedValue==NULL || FGPlaceAttribute.SubRegionSelectedValue=='0') && 
           (FGPlaceAttribute.AreaSelectedValue==NULL || FGPlaceAttribute.AreaSelectedValue=='0'))
                throw new CustomException ('请选择一个地域');   
          
         }catch(Exception ex)
             {
                 ApexPages.addMessages(ex);
                 return null;
             }
        if(ActivityType=='KA')
            AddParticipators('FG',mapParticipatorAreaFGList,ParticipatorAreaFGList,FGPlaceAttribute,false,ActivityInit);
        else
             AddParticipators('FG',mapParticipatorAreaFGList,ParticipatorAreaFGList,FGPlaceAttribute,ActivityInit.IsNcOrNotForRegion__c,ActivityInit);
        return null;
      }
       //添加两者兼无参与者 
      public PageReference AddOtherParticipator()
      {
        try{
          if((CoPlaceAttribute.RegionSelectedValue==NULL || CoPlaceAttribute.RegionSelectedValue=='0') && 
           (CoPlaceAttribute.SubRegionSelectedValue==NULL || CoPlaceAttribute.SubRegionSelectedValue=='0') && 
           (CoPlaceAttribute.AreaSelectedValue==NULL || CoPlaceAttribute.AreaSelectedValue=='0'))
                throw new CustomException ('请选择一个地域');   
         
         }catch(Exception ex)
             {
                 ApexPages.addMessages(ex);
                 return null;
             }
        AddParticipators('其它',mapParticipatorAreaOtherList,ParticipatorAreaOtherList,CoPlaceAttribute,ActivityInit.IsNcOrNotForRegion__c,ActivityInit);
        return null;
      }
      
      
      
   
       //添加参与者
       /*
      public void AddParticipators(String flag,Map<String,ActivityParticipatorEntry> mapParticipatorAreaList,List<ActivityParticipatorEntry> ParticipatorAreaList,CommonAttribute PlaceAttribute,boolean IsNC)
      {   
         outletDetail=new List<Participator_Detail_Outlet__c>();
         set<Id> AllParticipatorOutletId=new set<Id>();
       
         String sqlParticipator='select Outlet_Name__c from Participator_Detail_Outlet__c where Participator_Area__r.Activity_Name__c=\''+ActivityInit.id+'\' and OutletResourceType__c=\''+flag+'\' and Region__c=\''+PlaceAttribute.RegionSelectedValue+'\'';
        // if(PlaceAttribute.SubRegionSelectedValue!=null && PlaceAttribute.SubRegionSelectedValue!=''&& PlaceAttribute.SubRegionSelectedValue!='0')
             //    sqlParticipator+=' and SubRegion__c =\''+PlaceAttribute.SubRegionSelectedValue+'\'';
        // if(PlaceAttribute.AreaSelectedValue!=null && PlaceAttribute.AreaSelectedValue!=''&& PlaceAttribute.AreaSelectedValue!='0')
          //       sqlParticipator+=' and Area__c =\''+PlaceAttribute.SubRegionSelectedValue+'\'';          
         //查出已存在的门店
           for(Participator_Detail_Outlet__c par:database.query(sqlParticipator))
           {
                AllParticipatorOutletId.add(par.Outlet_Name__c);
            }
        //查出所有符合条件的outlet,按KA放入map中
         Map<String,Set<Id>> accountMap=new Map<String,Set<Id>>();
        Map<String,Set<Account >> accountsMap=new Map<String,Set<Account >>();
         String sql='select id,OwnerId,OutletRegion__c,OutletSubRegion__c,OutletArea__c, Chain_Customer__c,Outlet_Type__c,Channel__c from Account where Active_Status__c=\'正常营业\'' +Filter(PlaceAttribute.RegionSelectedValue,PlaceAttribute.SubRegionSelectedValue,PlaceAttribute.AreaSelectedValue,PlaceAttribute.KASelectedValue,PlaceAttribute.OutletTypeSelectedValue,PlaceAttribute.ChannelSelectedValue,IsNC);
         set<Id> ListCountLastActual=new  set<Id>();
         set<Account > ListCount=new  set<Account >();
         
         for(Account a:Database.Query(sql)){
           ListCountLastActual.add(a.id);
           ListCount.add(a);
         }
       //   System.assert(false,ListCountLastActual.size());
         //对于KA
        if(ActivityInit.Activity_Type__c=='KA' && PlaceAttribute.KASelectedValue==NULL){
          for(Account a:ListCount)
         {
           if(a.Chain_Customer__c!='' && a.Chain_Customer__c!=NULL){
               if(!accountMap.containsKey(a.Chain_Customer__c))
               {
                  Set<Id>  accList=new Set<Id>(); 
                  Set<Account >  accSet=new Set<Account >(); 
                    accList.add(a.id);
                    accSet.add(a);
                  accountMap.put(a.Chain_Customer__c,accList);
                  accountsMap.put(a.Chain_Customer__c,accSet);
                }
             else
             {  
                   Set<Id> accList=accountMap.get(a.Chain_Customer__c);
                    Set<Account >  accSet=accountsMap.get(a.Chain_Customer__c);
                   accList.add(a.id);
                   accSet.add(a);
                   accountMap.put(a.Chain_Customer__c,accList);
                   accountsMap.put(a.Chain_Customer__c,accSet);
              }
           }
         }
     }else{
       accountMap.put('kanotnull',ListCountLastActual);
     }
        //PA
    //  System.assert(false,accountMap);
       List<ParticipatorArea__c> paList=new List<ParticipatorArea__c>();
       Map<String,ParticipatorArea__c> parMap=new Map<String,ParticipatorArea__c>();
         //Set<String> areaList=new List<String>();
       String area='';
       if(PlaceAttribute.AreaSelectedValue!='0')
           area=PlaceAttribute.AreaSelectedValue;
         //查出所有Area
       String key=PlaceAttribute.RegionSelectedValue+PlaceAttribute.SubRegionSelectedValue+PlaceAttribute.AreaSelectedValue+PlaceAttribute.KASelectedValue+PlaceAttribute.OutletTypeSelectedValue+PlaceAttribute.ChannelSelectedValue;  
        
      for(String keyStr: accountMap.keySet()){
         Set<Id> accoutList=new Set<Id>();
         String ka=PlaceAttribute.KASelectedValue;
         if(ActivityInit.Activity_Type__c=='KA'&& PlaceAttribute.KASelectedValue==NULL){
           ka=keyStr;  
           accoutList=accountMap.get(keyStr);
           key=PlaceAttribute.RegionSelectedValue+PlaceAttribute.SubRegionSelectedValue+PlaceAttribute.AreaSelectedValue+keyStr+PlaceAttribute.OutletTypeSelectedValue+PlaceAttribute.ChannelSelectedValue;  
           }
         else{
           accoutList=ListCountLastActual;
         }
         integer countPar=0;
         if(accoutList.containsAll(AllParticipatorOutletId) || AllParticipatorOutletId.containsAll(accoutList)){
           
             if(accoutList.size()-AllParticipatorOutletId.size()>0)
                  countPar=accoutList.size()-AllParticipatorOutletId.size();
                    
         }else{
             countPar=accoutList.size();
         }
               //  System.assert(false,AllParticipatorOutletId);
           if(!mapParticipatorAreaList.containsKey(key)){
               ParticipatorArea__c par=new ParticipatorArea__c(Activity_Name__c=ActivityInit.id,
                                                                                  Region__c=PlaceAttribute.RegionSelectedValue,
                                                                                  Sub_region__c=PlaceAttribute.SubRegionSelectedValue,
                                                                                  Area__c=area,
                                                                                  OutletType__c=PlaceAttribute.OutletTypeSelectedValue,
                                                                                  Channel__c=PlaceAttribute.ChannelSelectedValue,
                                                                                 KA__c=ka,
                                                                                 Type__c=flag,
                                                                                 Outlet_Sum_Total__c=countPar
                                                                                 ); 
              //parMap.put(key,par); 
              if(countPar>0) 
                 paList.add(par);                                                                   
              ActivityParticipatorEntry entry=new ActivityParticipatorEntry (false,par);                                            
              mapParticipatorAreaList.put(key,entry);        
              if(mapParticipatorAreaList.size()>0)
               {
                     ParticipatorAreaList.clear();
                    for(ActivityParticipatorEntry  ee:mapParticipatorAreaList.values())
                     {
                          ParticipatorAreaList.add(new ActivityParticipatorEntry(false,ee.ParArea));
                     }  
                }                                                                   
               
              //  areaList.add(p);
         // System.assert(false,parMap);
       }
     }
        insert paList;
       
       for(ParticipatorArea__c pa:paList){
          //outletDetail.clear();
         
          Set<Account> accountSet=new Set<Account>();
          if(ActivityInit.Activity_Type__c=='KA' && PlaceAttribute.KASelectedValue==NULL){
            accountSet =accountsMap.get(pa.KA__C);
         }else{
           accountSet=ListCount;
         } 
       
          if(accountSet!=NULL){
          for(Account acc:accountSet){
            if(!AllParticipatorOutletId.contains(acc.Id)){
           
                     outletDetail.add(new Participator_Detail_Outlet__c(Outlet_Name__c=acc.id,
                                                                        Participator_Area__c=pa.Id,
                                                                        Outlet_Type__c='正常营业',
                                                                        OutletResourceType__c=flag,
                                                                        OwnerId=acc.OwnerId));
                  
              AllParticipatorOutletId.add(acc.Id);                                                                                      
               }
            } 
            }
             
               //  insert  outletDetail;     
          }
        //  System.assert(false,outletDetail);  
          insert  outletDetail;     
              
         PlaceAttribute.RegionSelectedValue='';
         PlaceAttribute.SubRegionSelectedValue='';
         PlaceAttribute.AreaSelectedValue='';
         PlaceAttribute.OutletTypeSelectedValue='';
         PlaceAttribute.ChannelSelectedValue='';
          PlaceAttribute.KASelectedValue='';             
        
          }
          */
             public void AddParticipators(String flag,Map<String,ActivityParticipatorEntry> mapParticipatorAreaList,List<ActivityParticipatorEntry> ParticipatorAreaList,CommonAttribute PlaceAttribute,boolean IsNc,Activity_Information__c ActivityInit)
      {   
         List<Participator_Detail_Outlet__c> outletDetail=new List<Participator_Detail_Outlet__c>();
         set<Id> AllParticipatorOutletId=new set<Id>();
       
         String sqlParticipator='select Outlet_Name__c from Participator_Detail_Outlet__c where Participator_Area__r.Activity_Name__c=\''+ActivityInit.id+'\' and OutletResourceType__c=\''+flag+'\' and Region__c=\''+PlaceAttribute.RegionSelectedValue+'\'';
          //查出已存在的门店
           for(Participator_Detail_Outlet__c par:database.query(sqlParticipator))
           {
                AllParticipatorOutletId.add(par.Outlet_Name__c);
            }
        //查出所有符合条件的outlet,按KA放入map中
         Map<String,Set<Id>> accountMap=new Map<String,Set<Id>>();
        Map<String,Set<Account >> accountsMap=new Map<String,Set<Account >>();
         String sql='select id,OwnerId,OutletRegion__c,OutletSubRegion__c,OutletArea__c, Chain_Customer__c,Outlet_Type__c,Channel__c from Account where Active_Status__c=\'正常营业\'' +Filter(PlaceAttribute.RegionSelectedValue,PlaceAttribute.SubRegionSelectedValue,PlaceAttribute.AreaSelectedValue,PlaceAttribute.KASelectedValue,PlaceAttribute.OutletTypeSelectedValue,PlaceAttribute.ChannelSelectedValue,IsNc);
         set<Id> ListCountLastActual=new  set<Id>();
         set<Account > ListCount=new  set<Account >();
         
         for(Account a:Database.Query(sql)){
           ListCountLastActual.add(a.id);
           ListCount.add(a);
         }
       //   System.assert(false,ListCountLastActual.size());
         //对于KA和SSY的KA   && ListCount.size()>0
        if((ActivityInit.Activity_Type__c=='KA' && PlaceAttribute.KASelectedValue==NULL) || (ActivityInit.Activity_Type__c=='SSY' && PlaceAttribute.KASelectedValue==NULL && flag=='KA' )){
      //  System.assert(false, sql);  
          for(Account a:ListCount)
         {
           if(a.Chain_Customer__c!='' && a.Chain_Customer__c!=NULL){
               if(!accountMap.containsKey(a.Chain_Customer__c))
               {
                  Set<Id>  accList=new Set<Id>(); 
                  Set<Account >  accSet=new Set<Account >(); 
                    accList.add(a.id);
                    accSet.add(a);
                  accountMap.put(a.Chain_Customer__c,accList);
                  accountsMap.put(a.Chain_Customer__c,accSet);
                }
             else
             {  
                   Set<Id> accList=accountMap.get(a.Chain_Customer__c);
                    Set<Account >  accSet=accountsMap.get(a.Chain_Customer__c);
                   accList.add(a.id);
                   accSet.add(a);
                   accountMap.put(a.Chain_Customer__c,accList);
                   accountsMap.put(a.Chain_Customer__c,accSet);
              }
           }
         }
     }else{
       accountMap.put('kanotnull',ListCountLastActual);
     }
        //PA
    //  System.assert(false,accountMap);
       List<ParticipatorArea__c> paList=new List<ParticipatorArea__c>();
         //Set<String> areaList=new List<String>();
       String subRegion='';
       String area='';
      if(PlaceAttribute.SubRegionSelectedValue!='0')
           subRegion=PlaceAttribute.SubRegionSelectedValue;
       if(PlaceAttribute.AreaSelectedValue!='0')
           area=PlaceAttribute.AreaSelectedValue;
         //查出所有Area
       String key=PlaceAttribute.RegionSelectedValue+subRegion+area+PlaceAttribute.KASelectedValue+PlaceAttribute.OutletTypeSelectedValue+PlaceAttribute.ChannelSelectedValue;  
        
      for(String keyStr: accountMap.keySet()){
         Set<Id> accoutList=new Set<Id>();
         String ka=PlaceAttribute.KASelectedValue;
         if((ActivityInit.Activity_Type__c=='KA' && PlaceAttribute.KASelectedValue==NULL) || (ActivityInit.Activity_Type__c=='SSY' && PlaceAttribute.KASelectedValue==NULL && flag=='KA' )){
           ka=keyStr;  
           accoutList=accountMap.get(keyStr);
           key=PlaceAttribute.RegionSelectedValue+subRegion+area+keyStr+PlaceAttribute.OutletTypeSelectedValue+PlaceAttribute.ChannelSelectedValue;  
          
           }
         else{
           accoutList=ListCountLastActual;
         }
         integer countPar=0;
         if(accoutList.containsAll(AllParticipatorOutletId) || AllParticipatorOutletId.containsAll(accoutList)){
           
          if(accoutList.size()-AllParticipatorOutletId.size()>0)
              countPar=accoutList.size()-AllParticipatorOutletId.size();              
         }else{
             countPar=accoutList.size();
         } 
           
           if(!mapParticipatorAreaList.containsKey(key)){
               ParticipatorArea__c par=new ParticipatorArea__c(Activity_Name__c=ActivityInit.id,
                                                                                  Region__c=PlaceAttribute.RegionSelectedValue,
                                                                                  Sub_region__c=subRegion,
                                                                                  Area__c=area,
                                                                                  OutletType__c=PlaceAttribute.OutletTypeSelectedValue,
                                                                                  Channel__c=PlaceAttribute.ChannelSelectedValue,
                                                                                 KA__c=ka,
                                                                                 Type__c=flag,
                                                                                   IsNCOrNot__c=IsNc,
                                                                                 Outlet_Sum_Total__c=countPar
                                                                                 ); 
              //parMap.put(key,par); 
              if(countPar>0) 
                 paList.add(par);                                                                   
              ActivityParticipatorEntry entry=new ActivityParticipatorEntry (false,par);                                            
              mapParticipatorAreaList.put(key,entry);      
            
              //System.assert(false, mapParticipatorAreaList);
              if(mapParticipatorAreaList.size()>0)
               {
                     ParticipatorAreaList.clear();
                    for(ActivityParticipatorEntry  ee:mapParticipatorAreaList.values())
                     {
                          ParticipatorAreaList.add(new ActivityParticipatorEntry(false,ee.ParArea));
                     }  
                }                                                                   
               
              //  areaList.add(p);
         // System.assert(false,parMap);
       }
     }
        insert paList;
       
       for(ParticipatorArea__c pa:paList){
          //outletDetail.clear();
         
          Set<Account> accountSet=new Set<Account>();
         if((ActivityInit.Activity_Type__c=='KA' && PlaceAttribute.KASelectedValue==NULL) || (ActivityInit.Activity_Type__c=='SSY' && PlaceAttribute.KASelectedValue==NULL && flag=='KA' )){
            accountSet =accountsMap.get(pa.KA__C);
         }else{
           accountSet=ListCount;
         } 
       
          if(accountSet!=NULL){
          for(Account acc:accountSet){
            if(!AllParticipatorOutletId.contains(acc.Id)){
           
                     outletDetail.add(new Participator_Detail_Outlet__c(Outlet_Name__c=acc.id,
                                                                        Participator_Area__c=pa.Id,
                                                                        Outlet_Type__c='正常营业',
                                                                        OutletResourceType__c=flag,
                                                                        OwnerId=acc.OwnerId));
                  
              AllParticipatorOutletId.add(acc.Id);                                                                                      
               }
            } 
            }
             
               //  insert  outletDetail;     
          }
        //  System.assert(false,outletDetail);  
          insert  outletDetail;     
              
         PlaceAttribute.RegionSelectedValue='';
         PlaceAttribute.SubRegionSelectedValue='';
         PlaceAttribute.AreaSelectedValue='';
         PlaceAttribute.OutletTypeSelectedValue='';
         PlaceAttribute.ChannelSelectedValue='';
          PlaceAttribute.KASelectedValue='';             
        
          }  
      //删除ET参与者  ，对应删除按钮 
     public PageReference DelParticipator()
     {      
      DelParticipators('ET',mapParticipatorAreaETList,ParticipatorAreaETList);
      return null;
    }
      //删除FG参与者  ，对应删除按钮 
     public PageReference DelFGParticipator()
     {
      DelParticipators('FG',mapParticipatorAreaFGList,ParticipatorAreaFGList);
      return null;
    }
      //删除两者兼无参与者  ，对应删除按钮 
     public PageReference DelOtherParticipator()
     {
      DelParticipators('其它',mapParticipatorAreaOtherList,ParticipatorAreaOtherList);  
      return null;
    }
        //删除参与者
      public void DelParticipators(String flag,Map<String,ActivityParticipatorEntry> mapParticipatorAreaList,List<ActivityParticipatorEntry> ParticipatorAreaList)
      {  
          for(Integer i=0;i<ParticipatorAreaList.size();i++)
             {
                 ActivityParticipatorEntry entry=ParticipatorAreaList[i];
                 if(entry.IsCheck)
                 {
                     String key=entry.ParArea.Region__c+entry.ParArea.Sub_region__c+entry.ParArea.Area__c+entry.ParArea.KA__c+entry.ParArea.OutletType__c+entry.ParArea.Channel__c;
                     mapParticipatorAreaList.remove(key);
                     ParticipatorAreaList.remove(i);
                    // System.assert(false,ParticipatorAreaList.size());
                     delete [select id from Participator_Detail_Outlet__c where Participator_Area__c=:entry.ParArea.Id];
                     delete [select id from ParticipatorArea__c where Id=:entry.ParArea.Id];
                     i--;
                 }
             }
      
      }
          //添加竞品信息
     public PageReference addCompetitionBrandAction()
     {
      
         if(CompetitionList==NULL)
             CompetitionList=new  List<ActivityCompetitionBrandEntry>();
             try
             {
                 if(CoPlaceAttribute.RegionPromotionTypeSelectedValue=='' || CoPlaceAttribute.RegionPromotionTypeSelectedValue==NULL)
                      throw new CustomException ('请选择竟品促销形式');
                 if(CoPlaceAttribute.RegionCostTypeSelectedValue=='' || CoPlaceAttribute.RegionCostTypeSelectedValue==NULL)
                      throw new CustomException ('请选择竞品费用形式');
                  if(CoPlaceAttribute.CostSourceSelectedValue=='' || CoPlaceAttribute.CostSourceSelectedValue==NULL)
                      throw new CustomException ('请选择竞品费用来源');
                  if(CompetitionList.size()>=8)
                      throw new CustomException ('竞品类型不能大于8个！');                  
                   for(ActivityCompetitionBrandEntry entry:CompetitionList)   
                   {
                       if(entry.ActivityCompetitionMsg.Competition_Cost_Source__c==CoPlaceAttribute.CostSourceSelectedValue &&
                          entry.ActivityCompetitionMsg.Competition_Cost_Type__c== CoPlaceAttribute.RegionCostTypeSelectedValue&&
                          entry.ActivityCompetitionMsg.Competition_Promotion_Type__c==CoPlaceAttribute.RegionPromotionTypeSelectedValue)
                              return null;
                   }
                    Activity_Competition_Brand_Information__c activity=new Activity_Competition_Brand_Information__c(Activity_Information__c=RecordId,
                                                                                                  Competition_Cost_Source__c=CoPlaceAttribute.CostSourceSelectedValue,
                                                                                                  Competition_Cost_Type__c=CoPlaceAttribute.RegionCostTypeSelectedValue,
                                                                                                   Competition_Promotion_Type__c=CoPlaceAttribute.RegionPromotionTypeSelectedValue );
                   CompetitionList.add(new ActivityCompetitionBrandEntry(false,activity));
                  // insert activity;
             }
             catch(Exception ex)
             {
                  ApexPages.addMessages(ex);
                 return null;
             }
             CoPlaceAttribute.RegionPromotionTypeSelectedValue='';
             CoPlaceAttribute.RegionCostTypeSelectedValue='';
             CoPlaceAttribute.CostSourceSelectedValue='';
             
             return null;
     }
     //删除竞品信息
      public PageReference DeleteCompetitionBrandAction()
      {
         for(Integer i=0;i<CompetitionList.size();i++)
         {
              ActivityCompetitionBrandEntry entry=CompetitionList[i];
             if(entry.IsCheck)
             {
                 CompetitionList.remove(i);
                // delete [select id from Activity_Competition_Brand_Information__c where id=:entry.ActivityCompetitionMsg.Id];
                 i--;
             }
         }
          return null;
      }
      
      public String Filter(String region,String SubRegion,String area,String KA,String outletType,String channel,boolean IsNC)
      {//System.assert(false,SubRegion);
            String filter='';
           if(region!='' && region!=NULL && region!='0')
          {
                            filter+=' and ';
                            filter+='OutletRegion__c=\''+region+'\'';
           }
          if(SubRegion!='' && SubRegion!=NULL && SubRegion!='0')
          {
                            filter+=' and ';
                            filter+='OutletSubRegion__c=\''+SubRegion+'\'';
           }
           if(area!='' && area!=NULL && area!='0')
          {
                            filter+=' and ';
                            filter+='OutletArea__c=\''+area+'\'';
           }
           if(KA!='' && KA!=NULL && KA!='0')
          {
                            filter+=' and ';
                            filter+='Chain_Customer__c=\''+KA+'\'';
           }
          if(outletType!='' && outletType!=NULL && outletType!='0')
          {
                            filter+=' and ';
                            filter+='Outlet_Type__c=\''+outletType+'\'';
           }
             if(channel!='' && channel!=NULL && channel!='0')
              {
                              filter+=' and ';
                             filter+='Channel__c=\''+channel+'\'';
              }
             if(IsNc==true)//是否是NC店
                  filter+=' and With_NC_or_not__c ='+IsNc;
              return filter;
      } 
      //保存活动前，如果活动ID不为空则先删除资源，     //? 关于ID问题
     public void deleteResource(){
                  if(ActivityInit.id!=NULL){
                  //  delete [select id from Resource_Allocation_Detail__c where  ActivityId__c=:RecordId];
                    delete [select id from CityResourceAllcation__c where  Activity_Information__c=:ActivityInit.id];
            //      delete [select id from Resource_Allocation__c where Activity_Information_Name__c=:ActivityInit.id ]; 
                                  
                  } 
       }     
       //保存资源
        public void saveActivityResourceEntry(){
             List<Resource_Allocation__c> InserRresourceList=new  List<Resource_Allocation__c>();
             List<Resource_Allocation__c> UpdateResourceList=new  List<Resource_Allocation__c>();
              //保存ET资源
               for(ActivityResourceEntry entry:ETResourceEntryList)
                  {
                  //   System.debug('**********'+entry.Res.Id);
                     if(entry.Res.Id!=null){
                        UpdateResourceList.add(entry.Res);
                      } else{
                       entry.Res.Activity_Information_Name__c=ActivityInit.id;
                       InserRresourceList.add(entry.Res);
                      }  
                  }
                  //保存FG资源
                  for(ActivityResourceEntry entry:FGResourceEntryList)
                  {
                     if(entry.Res.Id!=null){
                        UpdateResourceList.add(entry.Res);
                      } else{
                       entry.Res.Activity_Information_Name__c=ActivityInit.id;
                       InserRresourceList.add(entry.Res);
                      }  
                  }
                   insert InserRresourceList;
                   update UpdateResourceList;
        }
  
      public void SaveAndSubmit2()
      {  
            deleteResource();
            //查找所有参与者门店
            List<Participator_Detail_Outlet__c> DetailOutletList=new List<Participator_Detail_Outlet__c>();
             Set<Id> IdList=new Set<Id>();
             Set<Id> ETIdList=new Set<Id>();
             Set<Id> FGIdList=new Set<Id>();
             for(Participator_Detail_Outlet__c DetailOutlet:[select Id,OwnerId,Outlet_Name__c,KA__c,Area__c,OutletResourceType__c,Participator_Area__r.Type__c from Participator_Detail_Outlet__c where Participator_Area__r.Activity_Name__c=:ActivityInit.id])
             {
                 if(DetailOutlet.Participator_Area__r.Type__c=='ET')
                   ETIdList.add(DetailOutlet.Outlet_Name__c);  
                 else if(DetailOutlet.Participator_Area__r.Type__c=='FG')
                   FGIdList.add(DetailOutlet.Outlet_Name__c);  
                   
                 DetailOutletList.add(DetailOutlet);
                 IdList.add(DetailOutlet.Outlet_Name__c);  //保存所有门店的ＩＤ
             }   
             if(getTypeETOrFGOrAll!='两者兼无')
            {
                ActivityInit.Regional_Activity_Type__c='新活动';
                saveActivityResourceEntry();
                Map<String,Activity_Target_And_Allocation_Total__c> TargetAllocationTotal=new  Map<String,Activity_Target_And_Allocation_Total__c>();
                Map<String,integer> OutletCountMap=new  Map<String,integer>();
                List<Resource_Allocation_Detail__c> reourceOutletDetail=new List<Resource_Allocation_Detail__c>();       
                List<Resource_Allocation__c> radList=[select id,Activity_Information_Name__c,Product_Name__c,Product_Name__r.Pack_Size_C__c,Resource_Allocation_Number__c,Resource_Type__c from Resource_Allocation__c where Activity_Information_Name__c=:ActivityInit.id ];
             //  System.debug('***radList**'+radList.size()+'**'+DetailOutletList.size());
                 Map<Id,Decimal> OutletTargetList=new Map<Id,Decimal>();
                 decimal ETTotalTargetNum=0;// ETtarget总数 
                 decimal FGTotalTargetNum=0;// FGtarget总数        
                 for(Activity_Target_For_Outlet__c tar:[select Outlet__c,Target_Sum__c,KA_Chain_Customers__c,OutletArea__c from Activity_Target_For_Outlet__c where Outlet__c in: IdList])
                  {
                      OutletTargetList.put(tar.Outlet__c,tar.Target_Sum__c); //各门店target
                      if(ActivityInit.Activity_Type__c=='Region'){
                         if(TargetAllocationTotal.containsKey(tar.OutletArea__c)) {      //按区域汇总
                                   Activity_Target_And_Allocation_Total__c ataat=TargetAllocationTotal.get(tar.OutletArea__c);
                                   ataat.TargetNumber__c+=tar.Target_Sum__c;
                                   ataat.ResourceNumber__c=0;
                                   TargetAllocationTotal.put(tar.OutletArea__c,ataat);
                           }else{
                                    Activity_Target_And_Allocation_Total__c ataat=new Activity_Target_And_Allocation_Total__c();
                                    ataat.Activity_Information__c=ActivityInit.id;
                                    ataat.KAOrAreaName__c=tar.OutletArea__c;
                                    ataat.TargetNumber__c=tar.Target_Sum__c;
                                    ataat.Type__c='Area';
                                    TargetAllocationTotal.put(tar.OutletArea__c,ataat);
                            }
                        }      
                       for(Id etId:ETIdList){
                         if(tar.Outlet__c==etId)
                           ETTotalTargetNum+=tar.Target_Sum__c;
                       }
                      for(Id fgId:FGIdList){
                         if(tar.Outlet__c==fgId)
                           FGTotalTargetNum+=tar.Target_Sum__c;
                      }
                 }
                if(ActivityInit.Activity_Type__c=='Region'){
                   delete [select id from Activity_Target_And_Allocation_Total__c  where Activity_Information__c=:ActivityInit.id];
                   insert TargetAllocationTotal.values();
                }
                   for(Resource_Allocation__c entry:radList)//资源
                   {  
                       //System.debug('&&&'+entry.id+'&&'+entry.Product_Name__r.Pack_Size_C__c);   
                       decimal hasBeenAllocation=0;//已分配数 
                       reourceOutletDetail.clear();
                       for(Participator_Detail_Outlet__c pdo: DetailOutletList)//参与列表门店
                       {
                           if(entry.Resource_Type__c==pdo.Participator_Area__r.Type__c)
                           {
                            Resource_Allocation_Detail__c rad=new Resource_Allocation_Detail__c(); 
                            rad.Resource_Allocation__c=entry.id;
                              if(OutletTargetList.containsKey(pdo.Outlet_Name__c) )//target门店
                               {
                                   decimal num=(decimal)OutletTargetList.get(pdo.Outlet_Name__c);//获取门店总数
                                   pdo.TargetNumber__c=num;
                                   rad.Participator_Detail_Outlet__c=pdo.id;
                                   decimal rsValue;
                                   if(entry.Resource_Type__c=='ET')
                                     rsValue=(num/ETTotalTargetNum)*entry.Resource_Allocation_Number__c;     
                                   else
                                      rsValue=(num/FGTotalTargetNum)*entry.Resource_Allocation_Number__c;                        
                                   rad.Resource_Number__c=rsValue.round();     
                                   hasBeenAllocation+=rsValue.round();                        
                               }else{
                                   pdo.TargetNumber__c=0;
                                   rad.Participator_Detail_Outlet__c=pdo.id;
                                   rad.Resource_Allocation__c=entry.id;
                                   rad.Resource_Number__c=0;
                               }
                            reourceOutletDetail.add(rad);   
                            }
                       }
                      //     System.debug('***reourceOutletDetail**'+reourceOutletDetail.size());
                      //插入资源分配明细
                      commonMethod.getAdjustList(entry.Product_Name__r.Pack_Size_C__c,reourceOutletDetail,hasBeenAllocation,entry.Resource_Allocation_Number__c);
                   }
                 update DetailOutletList;
              }else{
                   ActivityInit.Regional_Activity_Type__c='竞品活动';
              }
                  //设置活动类型
                  if(ActivityInit.Activity_Type__c=='Region'){
             //     System.assert(false,ActivityInit.id);
                  delete [select id from Activity_Competition_Brand_Information__c where Activity_Information__c=:ActivityInit.id];//删除竟品信息
                  delete [select id from Activity_Competition_Brand_Detail__c where ActivityId__c=:RecordId];//删除竞品明细
                  List<Activity_Competition_Brand_Information__c> competitionInfoList=SaveCompetition();//保存竞品
                                    
                  List<Activity_Competition_Brand_Detail__c> competitionDetialList=new List<Activity_Competition_Brand_Detail__c>();
                  for(Activity_Competition_Brand_Information__c entry:competitionInfoList)
                  {
                       for(Participator_Detail_Outlet__c pdo: DetailOutletList)//参与列表门店
                       {
                         //  system.assert(false,pdo);
                           Activity_Competition_Brand_Detail__c acbd=new Activity_Competition_Brand_Detail__c(Activity_Competition_Brand_Information__c=entry.id,   
                                                                                                                                                                 Participator_Detail_Outlet__c=pdo.Id,OwnerId=pdo.OwnerId);
                            competitionDetialList.add(acbd);
                       }
                   }
                   insert competitionDetialList;
              }
        }
        //just save the activity
      public PageReference JustSaveActivity()
      {      
          try{
          
          if(ActivityInit.Name==NULL || ActivityInit.Name=='')
                throw new CustomException ('活动名称不能为空!');
           if(ActivityInit.Activity_Start_Date__c==NULL || ActivityInit.Activity_Start_Date__c<system.today())
                throw new CustomException('活动开始时间不能为空，且不能小于今天');
            if(ActivityInit.Activity_End_Date__c==NULL)
                throw new CustomException ('活动结束时间不能为空!');
            if(ActivityInit.Activity_Start_Date__c>ActivityInit.Activity_End_Date__c)
                throw new CustomException('活动开始时间不能大于活动结束时间');
            if(ActivityInit.ASMFinishDate__c==NULL || ActivityInit.ASMFinishDate__c>ActivityInit.Activity_Start_Date__c.addDays(-21))
                throw new CustomException('ASM完成调整时间不能为空，且必须在活动开始的前三周');
            if(ActivityInit.ASMConfirmDate__c==NULL || ActivityInit.ASMConfirmDate__c>ActivityInit.Activity_Start_Date__c.addDays(-21))
                throw new CustomException('ASM确认活动时间不能为空，且必须在活动开始的前三周');
            if(ActivityType=='Region'){
                if(getTypeETOrFGOrAll==null)
                   throw new CustomException ('请选择Region活动类型!');
                if(CompetitionList.size()==0)
                   throw new CustomException ('请添加竞品投入资料!');
                if(CompetitionList.size()>5)
                   throw new CustomException ('竞品投入资料数目不能超过5个!');
                 if(ActivityInit.RSMFinishApproveDate__c==NULL ||  ActivityInit.RSMFinishApproveDate__c>ActivityInit.Activity_Start_Date__c.addDays(-21))    
                    throw new CustomException('RSM完成审批时间不能为空，且必须在活动开始的前三周');
                 if(ActivityInit.RTMFinishApproveDate__c==NULL || ActivityInit.RTMFinishApproveDate__c>ActivityInit.Activity_Start_Date__c.addDays(-21))
                    throw new CustomException('RTM完成审批时间不能为空，且必须在活动开始的前三周');
                 if(ActivityInit.SRTMFinishApproveDate__c==NULL ||  ActivityInit.SRTMFinishApproveDate__c>ActivityInit.Activity_Start_Date__c.addDays(-21))
                    throw new CustomException('SRTM完成审批时间不能为空，且必须在活动开始的前三周');
               }else if(ActivityType=='KA'){
                  if(ActivityInit.KAMFinishAdjustDate__c==NULL || ActivityInit.KAMFinishAdjustDate__c>ActivityInit.Activity_Start_Date__c.addDays(-21))
                     throw new CustomException('KAM完成调整时间不能为空，且必须在活动开始的前三周');
                      
               }
               if(ActivityType=='Region'){
                if(getTypeETOrFGOrAll==null)
                   throw new CustomException ('请选择Region活动类型!');
                   }
            }catch(Exception ex)
             {
                 ApexPages.addMessages(ex);
                 return null;
             }
          if(ActivityType=='Region'){
      
              if(getTypeETOrFGOrAll=='两者兼无')
                  ActivityInit.Regional_Activity_Type__c='竞品活动';
              else
                  ActivityInit.Regional_Activity_Type__c='新活动';
          }
          insert ActivityInit;
          IsSave=true;     
          IsSubmit=true;  
          if(ActivityType=='Region')
               SaveCompetition();//保存竞品

       //   init();      
          pageReference pr = new pageReference('/apex/KAInitActivityForNTMKTList?id='+ActivityInit.id+'&&ActivityType='+ActivityType);     
          pr.setredirect(true);   
          return pr;
      }
      public List<Activity_Competition_Brand_Information__c> SaveCompetition()
      {
            //保存竞品
          List<Activity_Competition_Brand_Information__c> insertCompetitionList=new List<Activity_Competition_Brand_Information__c>();
          for(ActivityCompetitionBrandEntry entry:CompetitionList)
          {
              Activity_Competition_Brand_Information__c adbi=new Activity_Competition_Brand_Information__c();
              adbi.Activity_Information__c=ActivityInit.id;
              adbi.Competition_Cost_Source__c=entry.ActivityCompetitionMsg.Competition_Cost_Source__c;
              adbi.Competition_Cost_Type__c=entry.ActivityCompetitionMsg.Competition_Cost_Type__c;
              adbi.Competition_Promotion_Type__c=entry.ActivityCompetitionMsg.Competition_Promotion_Type__c;
              insertCompetitionList.add(adbi);
          }
          insert insertCompetitionList;
          return insertCompetitionList;
      }
    public PageReference SaveAllActivity()
      {
          
          SaveAndSubmit();
          update ActivityInit;
       //   LoadUtils();
        //  pageReference pr = new pageReference('/apex/KAInitActivityForNTMKTList?id='+ActivityInit.id+'&&ActivityType='+ActivityType);     
          pageReference pr = new pageReference('/'+ActivityInit.id);     
          pr.setredirect(true);   
          return pr;       
      }
      //Submit the Activity and change the stage
     public PageReference SubmitActivity()
      {
        if(ActivityInit.Activity_Type__c=='KA')
           ActivityInit.Activity_Stage__c='总部已发起活动';
        else if(ActivityInit.Activity_Type__c=='Region')
           ActivityInit.Activity_Stage__c='SRTM已发起活动';
        SaveAndSubmit();
        update ActivityInit;
  //     LoadUtils();
         //发送邮件给相应KA
        List<string> EmailList=new List<string>();
        EmailList=commonMethod.getUserEmailAddress('KAM',RecordId);
        if(EmailList.size()>0 && ActivityInit.Activity_Type__c=='KA'){
            User u=commonMethod.getUserInfo();
            String BodyString=u.Name+'已发布了【'+ActivityInit.Name+'】活动,请登陆凤凰系统进行相应的资源调整和竞品的添加,谢谢！';
            String subject='调整【'+ActivityInit.Name+'】活动的资源调整和竞品的添加等工作';
            EmailHander.SendMail(BodyString,EmailList,subject,'',null);  
        }
       
       pageReference pr = new pageReference('/'+ActivityInit.id);     
       pr.setredirect(true);   
       return pr;
      }
        //取消活动
        public PageReference CancelActivity()
        {
             if(RecordId!=NULL)
             {
                 ActivityInit.Activity_Stage__c='活动已取消';
                 ActivityInit.Activity_Type_State__c='取消';
                 update ActivityInit;
             }
            pageReference pr = new pageReference('/'+ActivityInit.id);     
            pr.setredirect(true);   
            return pr;
        }
      
    public void SaveAndSubmit()
      {    
            Set<Id> IdList=new Set<Id>(); 
            Set<Id> ETIdList=new Set<Id>();
            Set<Id> FGIdList=new Set<Id>();
            Map<Id,Decimal> OutletTargetList=new Map<Id,Decimal>();
            Map<String,integer> OutletCountMap=new Map<String,integer>();
            List<Participator_Detail_Outlet__c> DetailOutletList=new List<Participator_Detail_Outlet__c>();
            Map<String,Activity_Target_And_Allocation_Total__c> TargetAllocationTotal=new  Map<String,Activity_Target_And_Allocation_Total__c>(); //按KA,城市 ，类型来保存target
             for(Participator_Detail_Outlet__c DetailOutlet:[select Id,OwnerId,Outlet_Name__c,KA__c,TargetNumber__c,Area__c,OutletResourceType__c,Participator_Area__r.Type__c,City__c,SubRegion__c,Region__c from Participator_Detail_Outlet__c where Participator_Area__r.Activity_Name__c=:ActivityInit.id])
             {
                IdList.add(DetailOutlet.Outlet_Name__c);
               DetailOutletList.add(DetailOutlet);
               if(DetailOutlet.OutletResourceType__c=='ET')
                 ETIdList.add(DetailOutlet.Outlet_Name__c);
               else
                 FGIdList.add(DetailOutlet.Outlet_Name__c);
                 
                String ka='';
                if(ActivityInit.Activity_Type__c=='KA')
                    ka=DetailOutlet.KA__c;   
                if(!OutletCountMap.containsKey(ka+DetailOutlet.City__c+DetailOutlet.OutletResourceType__c)){
                   OutletCountMap.put(ka+DetailOutlet.City__c+DetailOutlet.OutletResourceType__c,1);
                }else{
                   integer count=OutletCountMap.get(ka+DetailOutlet.City__c+DetailOutlet.OutletResourceType__c)+1;
                   OutletCountMap.put(ka+DetailOutlet.City__c+DetailOutlet.OutletResourceType__c,count);
                }
                
                 if(!TargetAllocationTotal.containsKey(ka+DetailOutlet.City__c+DetailOutlet.OutletResourceType__c)){
                         Activity_Target_And_Allocation_Total__c ataat=new Activity_Target_And_Allocation_Total__c();
                         ataat.Activity_Information__c=RecordId;
                         ataat.Area__c=DetailOutlet.Area__c;
                         ataat.CityName__c=DetailOutlet.City__c;
                         ataat.KAName__c=ka;
                         ataat.Region__c=DetailOutlet.Region__c;
                         ataat.SubRegion__c=DetailOutlet.SubRegion__c;
                         ataat.TargetNumber__c=0;
                         ataat.Type__c=DetailOutlet.OutletResourceType__c;
                         TargetAllocationTotal.put(ka+DetailOutlet.City__c+DetailOutlet.OutletResourceType__c,ataat);
                       }
              }           
           if(ActivityInit.Regional_Activity_Type__c!='竞品活动')
            {
            // ActivityInit.Regional_Activity_Type__c='新活动';
            saveActivityResourceEntry();
            deleteResource();
          

            decimal ETTotalTargetNum=0;// ETtarget总数 
            decimal FGTotalTargetNum=0;// FGtarget总数     
            map<String,decimal> totalTargetByKA=new Map<String,decimal>();  //按KA保存总target
          //  map<String,decimal> totalTargetByRegion=new Map<String,decimal>()
        
           
            for(Activity_Target_For_Outlet__c tar:[select Outlet__c,Outlet__r.OutletArea__c,Outlet__r.CityName__c,Outlet__r.OutletRegion__c,Outlet__r.OutletSubRegion__c,Target_Sum__c,KA_Chain_Customers__c,OutletArea__c from Activity_Target_For_Outlet__c where Outlet__c in: IdList])
             {
             //KA活动按ka来分配城市资源，Region活动选择KA的按城市来分配城市资源
                OutletTargetList.put(tar.Outlet__c,tar.Target_Sum__c); //各门店target 
                String ka='';
                if(ActivityInit.Activity_Type__c=='KA')
                    ka=tar.KA_Chain_Customers__c;   
                       
             
                  //针对KA资源 
                  //ET
                
                  if(ETIdList.contains(tar.Outlet__c)){  
                        if(!totalTargetByKA.containsKey(ka+'ET')){
                           totalTargetByKA.put(ka+'ET',tar.Target_Sum__c);
                         }else{
                           decimal totTarget=totalTargetByKA.get(ka+'ET')+tar.Target_Sum__c;
                           totalTargetByKA.put(ka+'ET',totTarget);
                        }   
                                           
                         ETTotalTargetNum+=tar.Target_Sum__c;
                         Activity_Target_And_Allocation_Total__c ataat=TargetAllocationTotal.get(ka+tar.Outlet__r.CityName__c+'ET');
                         if(tar.Target_Sum__c!=NULL)
                           ataat.TargetNumber__c=ataat.TargetNumber__c+tar.Target_Sum__c;
                         TargetAllocationTotal.put(ka+tar.Outlet__r.CityName__c+'ET',ataat);
                 }
                     //FG
                    if(FGIdList.contains(tar.Outlet__c)){  
                       if(!totalTargetByKA.containsKey(ka+'FG')){
                           totalTargetByKA.put(ka+'FG',tar.Target_Sum__c);
                         }else{
                           decimal totTarget=totalTargetByKA.get(ka+'FG')+tar.Target_Sum__c;
                           totalTargetByKA.put(ka+'FG',totTarget);
                        }   
                        
                         FGTotalTargetNum+=tar.Target_Sum__c;
                         Activity_Target_And_Allocation_Total__c ataat=TargetAllocationTotal.get(ka+tar.Outlet__r.CityName__c+'FG');
                         if(tar.Target_Sum__c!=NULL)
                           ataat.TargetNumber__c=ataat.TargetNumber__c+tar.Target_Sum__c;
                         TargetAllocationTotal.put(ka+tar.Outlet__r.CityName__c+'FG',ataat);
                      
                  }  
                                      
             }   
            delete [select id from Activity_Target_And_Allocation_Total__c  where Activity_Information__c=:ActivityInit.id];
            insert TargetAllocationTotal.values();
            
                List<Resource_Allocation_Detail__c> reourceOutletDetail=new List<Resource_Allocation_Detail__c>();       
                List<CityResourceAllcation__c> CityreourceOutletDetail=new List<CityResourceAllcation__c>();       
                List<Resource_Allocation__c> radList=[select id,Activity_Information_Name__c,Product_Name__c,Product_Name__r.Pack_Size_C__c,Resource_Allocation_Number__c,Resource_Type__c from Resource_Allocation__c where Activity_Information_Name__c=:ActivityInit.id ];

                //   Map<String,CityResourceAllcation__c) craMap=new Map(String,CityResourceAllcation__c);//按KA,类型，城市存入Map
                   for(Resource_Allocation__c entry:radList)//资源
                   {  
                       integer hasBeenCityAllocation=0;
                       decimal hasBeenAllocation=0;//已分配数 
                       reourceOutletDetail.clear();
                       CityreourceOutletDetail.clear();
                       //插入CityResourceAllocation
                       for(Activity_Target_And_Allocation_Total__c ataat:TargetAllocationTotal.values())
                      {        
                        if(entry.Resource_Type__c==ataat.Type__c){
                               CityResourceAllcation__c cra=new CityResourceAllcation__c(); 
                                cra.Activity_Information__c=ActivityInit.id;
                                cra.Resource_Allocation__c=entry.id;
                                cra.Area__c=ataat.Area__c;
                                cra.CityName__c=ataat.CityName__c;
                                cra.KAName__c=ataat.KAName__c;
                               // cra.PackSize__c=entry.Product_Name__r.Pack_Size_C__c;
                                cra.Region__c=ataat.Region__c;
                                cra.SubRegion__c=ataat.SubRegion__c;
                                cra.Type__c=entry.Resource_Type__c;
                                cra.OutletNumber__c=OutletCountMap.get(ataat.KAName__c+ataat.CityName__c+ataat.Type__c);
                              //  decimal resourceNum=(ataat.TargetNumber__c/totalTargetByKA.get(ataat.KAName__c+ataat.Type__c))*entry.Resource_Allocation_Number__c;                    
                                decimal resourceNum=0;
                                if(entry.Resource_Type__c=='ET')
                                   resourceNum=(ataat.TargetNumber__c/ETTotalTargetNum)*entry.Resource_Allocation_Number__c;         
                                else
                                   resourceNum=(ataat.TargetNumber__c/FGTotalTargetNum)*entry.Resource_Allocation_Number__c;                           
                                cra.ResourceNumber__c=resourceNum.round();
                                hasBeenCityAllocation+=resourceNum.round().intValue();
                                CityreourceOutletDetail.add(cra); 
                          }
                       }     
                       //插入 ResourceAllocationDetail
                       
                       for(Participator_Detail_Outlet__c pdo: DetailOutletList)//参与列表门店
                       {
                           if(entry.Resource_Type__c==pdo.Participator_Area__r.Type__c)
                           {
                              Resource_Allocation_Detail__c rad=new Resource_Allocation_Detail__c(); 
                              rad.Resource_Allocation__c=entry.id;
                              if(OutletTargetList.containsKey(pdo.Outlet_Name__c) )//target门店
                               {
                                   decimal num=(decimal)OutletTargetList.get(pdo.Outlet_Name__c);//获取门店总数
                                   pdo.TargetNumber__c=num;
                                   rad.Participator_Detail_Outlet__c=pdo.id;
                                   decimal rsValue;
                                   if(entry.Resource_Type__c=='ET')
                                     rsValue=(num/ETTotalTargetNum)*entry.Resource_Allocation_Number__c;     
                                   else
                                      rsValue=(num/FGTotalTargetNum)*entry.Resource_Allocation_Number__c;                        
                                   rad.Resource_Number__c=rsValue.round();     
                                   hasBeenAllocation+=rsValue.round();                      
                               }else{
                                   pdo.TargetNumber__c=0;
                                   rad.Participator_Detail_Outlet__c=pdo.id;
                                   rad.Resource_Allocation__c=entry.id;
                                   rad.Resource_Number__c=0; 
                               }
                            reourceOutletDetail.add(rad);   
                            }
                       }
                        commonMethod.getAdjustList(entry.Product_Name__r.Pack_Size_C__c,reourceOutletDetail,hasBeenAllocation,entry.Resource_Allocation_Number__c);                   
                     
                  //   System.assert(false,radList.size());
                        insert commonMethod.ReturnCityAdjustList(CityreourceOutletDetail,hasBeenCityAllocation,entry.Resource_Allocation_Number__c.intValue());
                     }           
                     update DetailOutletList;
                }else{
                   ActivityInit.Regional_Activity_Type__c='竞品活动';
                 }
                  //设置活动类型
                  if(ActivityInit.Activity_Type__c=='Region'){
             //     System.assert(false,ActivityInit.id);
                  delete [select id from Activity_Competition_Brand_Information__c where Activity_Information__c=:ActivityInit.id];//删除竟品信息
                  delete [select id from Activity_Competition_Brand_Detail__c where ActivityId__c=:RecordId];//删除竞品明细
                  List<Activity_Competition_Brand_Information__c> competitionInfoList=SaveCompetition();//保存竞品
                                    
                  List<Activity_Competition_Brand_Detail__c> competitionDetialList=new List<Activity_Competition_Brand_Detail__c>();
                  for(Activity_Competition_Brand_Information__c entry:competitionInfoList)
                  {  
                       Set<Id> OutletIdList=new Set<Id>(); 
                       for(Participator_Detail_Outlet__c pdo:DetailOutletList)//参与列表门店
                       {
                         if(!OutletIdList.contains(pdo.Outlet_Name__c)){
                            OutletIdList.add(pdo.Outlet_Name__c);
                            Activity_Competition_Brand_Detail__c acbd=new Activity_Competition_Brand_Detail__c(Activity_Competition_Brand_Information__c=entry.id,   
                                                                                                                                                                 Participator_Detail_Outlet__c=pdo.Id,OwnerId=pdo.OwnerId);
                            competitionDetialList.add(acbd);
                          }
                       }
                   }
                   insert competitionDetialList;
              }
              
        }      
   public PageReference ParticipatorOnCheckAction()
        {
            try
            {
             if(ActivityInit.Activity_Stage__c=='草稿' && (ActivityInit.Activity_Type__c=='Region' || ActivityInit.Activity_Type__c=='Region(剩余资源)')){   
               
                    delete [select id from Participator_Detail_Outlet__c where Participator_Area__r.Activity_Name__c=:recordId];
                    delete [select id from ParticipatorArea__c where Activity_Name__c=:recordId];
                    if(ActivityInit.Regional_Activity_Type__c=='新活动'){
                         mapParticipatorAreaETList.clear();
                         ParticipatorAreaETList.clear();
                         mapParticipatorAreaFGList.clear();
                         ParticipatorAreaFGList.clear();
                    }else{
                         mapParticipatorAreaOtherList.clear();
                         ParticipatorAreaOtherList.clear(); 
                    }
         
              }
            }
            catch(DMLException ex)
            {
              
                ApexPages.addMessages(new CustomException('由于数据量大，请分多次删除数据'));
                   return null;
            }
                return null;
        }        
    
}